<template>
	<div>
        <Card dis-hover style="margin: 10px">
             <Form ref="form1" :model="form1" :label-width="120">
                 <Row :gutter="16" class="query-form2">
                     <i-col span="8">
                         <FormItem label="流程图名称：">
                             <Input class="query-form-el" type="text" v-model="procinstName" placeholder="请输入流程名称"></Input>
                         </FormItem>
                     </i-col>
                     <i-col span="8">
                         <FormItem label="上报人：">
                             <Input class="query-form-el" type="text" v-model="userName" placeholder="请输入上报人"></Input>
                         </FormItem>
                     </i-col>
                     <i-col span="8">
                         <div style="float: right">
                             <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                             <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                         </div>
                     </i-col>
                 </Row>
            </Form>
            <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns1" no-data-text="没有查询到相关数据！"
                   :data="dataTable" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
            <Row type="flex" justify="end" >
                <i-col>
                    <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                          @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
                </i-col>
            </Row>
            <Modal :transfer=false v-model="model1"  :width=900>
                <Tabs>
                    <TabPane label="历史记录">
                        <Table ref='table' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                               :loading="loading2"
                               :data="history" width="100%" :height="450" highlight-row stripe size="small"></Table>
                    </TabPane>
                    <TabPane label="流程图">
                        <div style="height: 450px; overflow-y: auto; overflow-x: auto">
                            <img :src="imgUrl">
                        </div>
                    </TabPane>
                    <TabPane label="人员变更记录">
                        <Table ref='table' border :columns="columns3" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                               :loading="loading2"
                               :data="historyChange" width="100%" :height="450" highlight-row stripe size="small"></Table>
                    </TabPane>
                </Tabs>
                <div slot="footer">
                    <Button @click="model1=false" class="ivu-btn-save">关闭</Button>
                </div>
            </Modal>
        </Card>
	</div>
</template>

<script>
	import {Api} from '../../../api/index.js'
    import { sessionStorage, cookie } from '../../../common/cacheUtils.js';
	export default {
        components: {
        },
		data() {
			return {
                procinstName:'',
                userName:'',
                dateRange:["",""],
                createDate:'',
                endDate:'',
                imgUrl: '',
                switchFlag:false,
                loading: false,
                loading2: false,
                form1: {},
                //分页参数
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
				columns1: [
				    {
                        type: 'index',
                        title: '序号',
                        minWidth: 80,
						 align: 'center',
					 },
					{
                        minWidth: 250,
                        title: '流程名称',
                        align: 'center',
                        key: 'procinstName',
					},
					{
                        minWidth: 120,
						title: '流程状态',
						key: 'procinstStateName',
						align: 'center',
					},
					{
                        minWidth: 150,
						title: '上报时间',
						key: 'createDate',
                        align: 'center',
                        render:(h,params)=>{
                            return h('div',[
                                (this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd'))
                            ]);
                        }
					},
					{
                        minWidth: 150,
						title: '上报人',
						key: 'userName',
						align: 'center'
					},
					{
                        minWidth: 200,
						title: '当前任务节点名称',
						key: 'taskName',
						align: 'center',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.taskName || '--')
                            ]);
                        }
					},
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 180,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('a', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: "14px"
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params.row);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('a', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                            this.showHistory(params.row);
                                        }
                                    }
                                },'审批记录')
                            ]);
                        }
                    }
				],
                dataTable: [],
                tableHeight : 10,
                model1 : false,
                model2 : false,
                history : [],
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        width: 180,
                        title: '审批时间',
                        key: 'endTime',
                        align: 'center',
                    },
                    {
                        width: 185,
                        title: '节点名称',
                        key: 'name',
                        align: 'center',
                    },
                    {
                        width: 120,
                        title: '审批人',
                        key: 'userName',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '审批意见',
                        key: 'route',
                        align: 'center'
                    },
                    {
                        width: 200,
                        title: '备注',
                        key: 'opinions',
                        align: 'center'
                    },
                ],
                columns3: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        title: '变更节点',
                        key: 'taskName',
                        align: 'center',
                    },
                    {
                        title: '变更前审批人',
                        key: 'oldUserName',
                        align: 'center',
                    },
                    {
                        title: '变更后审批人',
                        key: 'newUserName',
                        align: 'center',
                    },
                ],
                historyChange: []
			}
		},
        watch: {
            "model1":function(qw,er){
                if(!qw){
                    this.imgUrl = '';
                }
            },
        },
		mounted: function() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 215;
			this.query();
        },
		methods: {
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },

            showData(row) {
                let user = sessionStorage('userId').getObject('userId');
                let formKey = row.formKey;
                let taskName = '';
                if(formKey == 'hidHazardForm'){
                    taskName = '隐患上报流程'
                }else if(formKey == 'apsgForm'){
                    taskName = '隐患排查流程'
                }else{
                    taskName = row.taskName;
                }
                let data = {
                    taskName: row.procinstName,
                    taskId : row.taskId,
                    workId: row.workId,
                    procinstId : row.procinstId,
                    close:false,
                    currentTask: row.currentTask,
                    userId : user.userId,
                    viewFlag: true,
                    status: 'self'
                }
                this.$router.push({ path: "/"+ formKey, query: data});

            },
            showHistory(row) {
                this.model1 = true;
                this.loading2 = true;
                this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
                    this.history = res.data;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                });
                this.$http.get(Api.getHistory + '/change/' + row.procinstId, {params: {}}).then((res) => {
                    this.historyChange = res.data;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                });
            },
            reset(){
                this.dateRange = "";
                this.userName = "";
                this.procinstName = "";
            },
            query() {
                this.loading = true;
                this.createDate = "";
                this.endDate = "";
                if (this.dateRange[0]!=""&&this.dateRange[1]!=""){
                    this.createDate =  this.formatDate(new Date(this.dateRange[0]), 'yyyy-MM-dd');
                    this.endDate = this.formatDate(new Date(this.dateRange[1]), 'yyyy-MM-dd');
                }
                let user = sessionStorage('userId').get('userId');
                let userJson = JSON.parse(user);
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    // createUserId :userJson.userId,
                    procinstName: this.procinstName,
                    startDate: this.createDate != "" ? this.createDate + " 00:00:00":"",
                    endDate: this.endDate != ""?this.endDate + " 23:59:59":"",
                }
                let url = Api.getSelfList;
                this.$http.get(url,  {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.dataTable.map(item=>{
                        if(item.procinstState =='0' || item.procinstState ==null){
                            item.procinstStateName = '未上报';
                        }else if(item.procinstState =='1'){
                            item.procinstStateName = '已上报';
                        }else if(item.procinstState =='2'){
                            item.procinstStateName = '被退回';
                        }else if(item.procinstState =='3'){
                            item.procinstStateName = '已审批';
                        }
                    })
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.loading = false;
                    this.$Message.error("数据获取失败")
                })
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },

        },
	}
</script>
<style lang='css' scoped>
    @import '../../../index.css';
</style>
